<?php
/**
 * 功能: 定时任务
 * User: WD
 * Date: 2018/10/12 0012
 * Time: 14:59
 */

namespace app\index\command;

use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Db;

class Timing extends Command{
    protected function configure()
    {
        $this->setName('timing')->setDescription('Here is the remark ');
    }

    protected function execute(Input $input, Output $output){
        $output->writeln("TestCommand:");
        /*用不超时*/
        ini_set('max_execution_time', 0);
        $this->order_real();
    }
    /**
     * 实时查询订单
     */
    public function order_real(){
        // $data   =  strtotime(' 2018-10-12 15:24:29');
        $a = strtotime('-20 minute');
        $time  = date('Y-m-d H:i:s',$a);
        $time1 = urlencode($time);
        $vkey  = config('vkey');
        $url   = "http://api.vephp.com/order?vekey=V00000077Y64731531&start_time=".$time1."&span=1200";
        $data  = file_get_contents($url);
        $res   = json_decode($data,true,512,JSON_BIGINT_AS_STRING);
        $a = $res['data'][0]['tk_status'];
       // dump($a);
       //   print_r($res);die;

        $error = isset($res['errcode'])?$res['errcode']:$res['error'];
        if($error){
            return json(['msg'=>$error,'ok'=>false]);
        }else{

            $result = $res['data'];

            $arr = $arrs = [];
            $i = 0;
            if(!empty($result)){
                foreach($result as $k=>$v){
                    if(strpos($v['site_name'],'买就省')!==false){
                        $arr['user_id'] = Db::name('pid')->where('adzone_id',$v['adzone_id'])->value('user_id');;
                        $arr['create_time'] = $v['create_time'];
                        $arr['order_num'] = $v['trade_id'];//订单号
                        $arr['parent_order_num'] = $v['trade_parent_id'];//父订单号
                        $arr['goods_id'] = $v['num_iid'];
                        $arr['info'] = $v['item_title'];
                        $arr['shop'] = $v['seller_shop_title'];
                        $arr['nick'] = isset($v['seller_nick'])?$v['seller_nick']:'';//旺旺名
                        $arr['amount'] = $v['item_num'];
                        $arr['price'] = $v['price'];

                        //淘客订单状态，3：订单结算，12：订单付款， 13：订单失效，14：订单成功
                        if(intval($v['tk_status'])=='12'){
                            $arr['state'] = 1;
                        }elseif(intval($v['tk_status'])=='3'){
                            $arr['state'] = 2;
                        }elseif(intval($v['tk_status'])=='13'){
                            $arr['state'] = 3;
                        }elseif(intval($v['tk_status'])=='14'){
                            $arr['state'] = 4;
                        }else{
                            $arr['state'] = 0;
                        }
                        $arr['income_rate'] = $v['income_rate'];//收入比率
                        $arr['divide_tate'] = $v['commission_rate']/100;//分成比率

                        $arr['pay'] = isset($v['pay_price'])?$v['pay_price']:$v['alipay_total_price'];//实际支付金额
                        $arr['effect'] = $v['pub_share_pre_fee'];//预估收入
                        $arr['settle'] = $v['alipay_total_price']?$v['alipay_total_price']:'0';

                        $arr['expect'] = $v['commission'];//佣金预计收入


                        $arr['finish_time'] = isset($v['earning_time'])?$v['earning_time']:'';
                        $arr['yj_rate'] = $v['total_commission_rate'];
                        $arr['yj_sum'] = isset($v['total_commission_fee'])?$v['total_commission_fee']:(round($arr['settle'] * ($v['total_commission_rate']), 2));;//佣金

                        $arr['member_actual'] = round(($v['commission']/2)*$arr['amount'],2);//会员佣金实际收入
                        $arr['member_expect'] = round(($arr['amount']*$arr['yj_rate']*$arr['settle'])/2,2);//预计会员佣金


                        $arr['subsidy_rate'] = $v['subsidy_rate'];
                        $arr['subsidy'] = isset($v['subsidy_fee'])?$v['subsidy_fee']:(round($arr['price'] * ($v['subsidy_rate']), 2));//补贴金额
                        $arr['goods_type'] = $v['auction_category'];
                        /*$arr['media_id'] = $v['site_id'];
                        $arr['media'] = $v['site_name'];*/
                        $arr['adzone_id'] = $v['adzone_id'];
                        $arr['adzone_name'] = $v['adzone_name'];

                        //订单用户添加
                        $userData = [
                            'user_id'=>$arr['user_id'],
                            'order_num'=> $arr['order_num'] ,
                            'create_time'=>time()
                        ];
                        $check_user = Db::name('user_order')->where('order_num',$arr['order_num'])->find();
                        if(empty($check_user)){
                            Db::name('user_order')->insert($userData);
                        }

                        if ($arr['state'] == 2) {
                            //订单结算
                            $user = Db::name('user')->where('id', $arr['user_id'])->find();
                            $amount = round($v['total_commission_fee'] / 2,2);
                            $a = [
                                'user_id' => $arr['user_id'],
                                'commission' => $amount,
                                'time' => strtotime($arr['finish_time']),
                                'state' => 1,//1收入，2支出
                                'type' => 1,//1自己订单收入，2粉丝提成收入，3用户提现支出
                                'remark' => '订单' . $arr['order_num'] . '收入'
                            ];
                            $check_profit = Db::name('profit')
                                ->where('user_id', $arr['user_id'])
                                ->where('remark', '订单' . $arr['order_num'] . '收入')
                                ->find();
                            if (empty($check_profit)) {
                                Db::name('profit')->insert($a);
                                Db::name('user')->where('id',$arr['user_id'])->setInc('total',$amount);
                                Db::name('user')->where('id',$arr['user_id'])->setInc('commission',$amount);
                            }
                            $parent_id = $user['parent_id'];
                            if($parent_id){
                                $parent = Db::name('user')->where('id',$parent_id)->find();
                                $ticheng = 0;
                                if($parent['status']==3||$parent['status']==4){
                                    $rule = Db::name('partner_rule')->where('status',$parent['status'])->find();
                                    $level1 = $rule['level1']/100;
                                    $ticheng = round($amount*$level1,2);
                                }

                                $arr1 = [
                                    'user_id' => $parent_id,
                                    'commission' => $ticheng,
                                    'time' => strtotime($arr['finish_time']),
                                    'state' => 1,//1收入，2支出
                                    'type' => 2,//1自己订单收入，2粉丝提成收入，3用户提现支出
                                    'remark' => '粉丝' . $parent_id . '订单' . $arr['order_num'] . '收入'
                                ];
                                $check_profit = Db::name('profit')
                                    ->where('user_id', $parent_id)
                                    ->where('remark', '粉丝' . $arr['user_id'] . '订单' . $arr['order_num'] . '收入')
                                    ->find();
                                if (empty($check_profit)) {
                                    Db::name('profit')->insert($arr1);
                                    Db::name('user')->where('id',$parent_id)->setInc('total',$ticheng);
                                    Db::name('user')->where('id',$parent_id)->setInc('commission',$ticheng);
                                    Db::name('user')->where('id',$parent_id)->setInc('rebate',$ticheng);
                                }
                                $grandsire = Db::name('user')->where('id',$parent['parent_id'])->find();
                                if($grandsire){
                                    //祖籍
                                    $t2 = 0;
                                    if($grandsire['status']==3||$grandsire['status']==4){
                                        $rule = Db::name('partner_rule')->where('status',$grandsire['status'])->find();
                                        $level2 = $rule['level2']/100;
                                        $t2 = round($amount*$level2,2);
                                    }

                                    $arr2 = [
                                        'user_id' => $grandsire['id'],
                                        'commission' => $t2,
                                        'time' => strtotime($arr['finish_time']),
                                        'state' => 1,//1收入，2支出
                                        'type' => 2,//1自己订单收入，2粉丝提成收入，3用户提现支出
                                        'remark' => '粉丝' . $grandsire['id'] . '订单' . $arr['order_num'] . '收入'
                                    ];
                                    $check_profit = Db::name('profit')
                                        ->where('user_id', $grandsire['id'])
                                        ->where('remark', '粉丝' . $arr['user_id'] . '订单' . $arr['order_num'] . '收入')
                                        ->find();
                                    if (empty($check_profit)) {
                                        Db::name('profit')->insert($arr2);
                                        Db::name('user')->where('id',$grandsire['id'])->setInc('total',$t2);
                                        Db::name('user')->where('id',$grandsire['id'])->setInc('commission',$t2);
                                        Db::name('user')->where('id',$grandsire['id'])->setInc('rebate',$t2);
                                    }

                                }
                            }

                        }

                        $check = Db::name('goods_order')
                            ->where('goods_id',$arr['goods_id'])
                            ->where('order_num',$arr['order_num'])
                            ->find();
                        if ($check) {
                            $success = Db::name('goods_order')->where('goods_id', $arr['goods_id'])->where('order_num', $arr['order_num'])->update($arr);
                        } else {
                            $arrs[] = $arr;
                        }
                        $i++;

                    }

                }

                Db::startTrans();
                try{
                    foreach($arrs as $k=>$v){
                        $check = Db::name('goods_order')
                            ->where('goods_id',$v['goods_id'])
                            ->where('order_num',$v['order_num'])
                            ->find();

                        if(empty($check)){
                            $success = Db::name('goods_order')->insertAll($arrs); //批量插入数据
                        }else{
                            $success = 0;
                        }

                    }

                    foreach($arrs as $k =>$v){

                            if ($v['state'] == 2) {
                                //订单结算
                                $user = Db::name('user')->where('id', $v['user_id'])->find();
                                $amount = round($v['yj_sum'] / 2,2);
                                $arr = [
                                    'user_id' => $v['user_id'],
                                    'commission' => $amount,
                                    'order_num' => $v['order_num'],
                                    'time' => strtotime($v['finish_time']),
                                    'state' => 1,//1收入，2支出
                                    'type' => 1,//1自己订单收入，2粉丝提成收入，3用户提现支出
                                    'remark' => '订单' . $v['order_num'] . '收入'
                                ];
                                $check_profit = Db::name('profit')
                                    ->where('user_id', $v['user_id'])
                                    ->where('remark', '订单' . $v['order_num'] . '收入')
                                    ->find();
                                if (empty($check_profit)) {
                                    Db::name('profit')->insert($arr);
                                    Db::name('user')->where('id',$v['user_id'])->setInc('total',$amount);
                                    Db::name('user')->where('id',$v['user_id'])->setInc('commission',$amount);
                                }
                                $parent_id = $user['parent_id'];
                                if($parent_id){
                                    $parent = Db::name('user')->where('id',$parent_id)->find();
                                    $ticheng = 0;
                                    if($parent['status']==3||$parent['status']==4){
                                        $rule = Db::name('partner_rule')->where('status',$parent['status'])->find();
                                        $level1 = $rule['level1']/100;
                                        $ticheng = round($amount*$level1,2);
                                    }
                                    $arr1 = [
                                        'user_id' => $parent_id,
                                        'commission' => $ticheng,
                                        'order_num' => $v['order_num'],
                                        'time' => strtotime($v['finish_time']),
                                        'state' => 1,//1收入，2支出
                                        'type' => 2,//1自己订单收入，2粉丝提成收入，3用户提现支出
                                        'remark' => '粉丝' . $v['user_id'] . '订单' . $v['order_num'] . '收入'
                                    ];
                                    $check_profit = Db::name('profit')
                                        ->where('user_id', $parent_id)
                                        ->where('remark', '粉丝' . $v['user_id'] . '订单' . $v['order_num'] . '收入')
                                        ->find();
                                    if (empty($check_profit)) {
                                        Db::name('profit')->insert($arr1);
                                        Db::name('user')->where('id',$parent_id)->setInc('total',$ticheng);
                                        Db::name('user')->where('id',$parent_id)->setInc('commission',$ticheng);
                                        Db::name('user')->where('id',$parent_id)->setInc('rebate',$ticheng);
                                    }
                                    $grandsire = Db::name('user')->where('id',$parent['parent_id'])->find();
                                    if($grandsire){
                                        //祖籍
                                        $t2 = 0;
                                        if($grandsire['status']==3||$grandsire['status']==4){
                                            $rule = Db::name('partner_rule')->where('status',$grandsire['status'])->find();
                                            $level2 = $rule['level2']/100;
                                            $t2 = round($amount*$level2,2);
                                        }
                                        $arr2 = [
                                            'user_id' => $grandsire['id'],
                                            'commission' => $t2,
                                            'order_num' => $v['order_num'],
                                            'time' => strtotime($v['finish_time']),
                                            'state' => 1,//1收入，2支出
                                            'type' => 2,//1自己订单收入，2粉丝提成收入，3用户提现支出
                                            'remark' => '粉丝' . $v['user_id'] . '订单' . $v['order_num'] . '收入'
                                        ];
                                        $check_profit = Db::name('profit')
                                            ->where('user_id', $grandsire['id'])
                                            ->where('remark', '粉丝' . $v['user_id'] . '订单' . $v['order_num'] . '收入')
                                            ->find();
                                        if (empty($check_profit)) {
                                            Db::name('profit')->insert($arr2);
                                            Db::name('user')->where('id',$grandsire['id'])->setInc('total',$t2);
                                            Db::name('user')->where('id',$grandsire['id'])->setInc('commission',$t2);
                                            Db::name('user')->where('id',$grandsire['id'])->setInc('rebate',$t2);
                                        }

                                    }
                                }

                            }



                        }

                    // 提交事务
                    Db::commit();
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                }

            }


        }


    }

}